(function () {		
//定义当前使用的开源组建的版本号
var OPEN_JS_T = {
    Jpegmeta : "201508011808" ,
    JpegEncoder : "201508011808" ,
    ImageCompress : "201508011808"
};
JS.load("/Public/Js/utils/jpegmeta.js" ,OPEN_JS_T.Jpegmeta);
JS.load("/Public/Js/utils/jpeg.encoder.basic.js" ,OPEN_JS_T.JpegEncoder);
JS.load("/Public/Js/utils/image_compress.js" ,OPEN_JS_T.ImageCompress);	
var uploadObj;
window.photo = {
		
maxUpload : 8,
// 上传信息 主要是 id 对应信息
uploadInfo: {},
// 上传队列，里面保存的是 id
uploadQueue: [],
// 预览队列，里面保存的是 id
previewQueue: [],
// 请求对象
xhr: {},
// 是否有任务正在上传
isBusy: false,
// fid
fid : 0,
tid : 0,
pId : 0,
qunId : 0,
	
    countUpload: function() {
        var num = 0;
        $.each(photo.uploadInfo, function(i, n) {
                if (n) {
                ++ num;
                }
        });

        return num;
    },

    getbuilder: function(s, filename, filedata, boundary) {
        var dashdash = '--',
        crlf = '\r\n',
        builder = '';

        for(var i in s.uploadformdata) {
            builder += dashdash;
            builder += boundary;
            builder += crlf;
            builder += 'Content-Disposition: form-data; name="' + i + '"';
            builder += crlf;
            builder += crlf;
            builder += s.uploadformdata[i];
            builder += crlf;
        }

        builder += dashdash;
        builder += boundary;
        builder += crlf;
        builder += 'Content-Disposition: form-data; name="' + s.uploadinputname + '"';
        builder += '; filename="' + filename + '"';
        builder += crlf;

        builder += 'Content-Type: application/octet-stream';
        builder += crlf;
        builder += crlf;

        builder += filedata;
        builder += crlf;

        builder += dashdash;
        builder += boundary;
        builder += dashdash;
        builder += crlf;
        return builder;
    },
	has_upload_list:function(ul,act){
		var textarea = ul.prev();
		var lis=$(ul).find("li");
		var imgList=new Array();
		$.each(lis,function(i,v){
			var imgs={};
			if($(v).attr("url")){
				imgs['file_url']=	$(v).attr("url");
				imgs['file_name']=	$(v).attr("name");
				imgList.push(imgs);
			}
		})
		if(imgList.length>0){
			textarea.val(JSON.stringify(imgList));
		}else{
			textarea.val("");	
		}
		if(act=="del"){
			textarea.trigger("BoxUploadDel");
		}
		if(act=="add"){
			textarea.trigger("BoxUploadAdd");
		}
		console.log(textarea.val());
	},
    // 图片预览
    uploadPreview: function(id) {

        var reader = new FileReader();
        var uploadBase64;
        var conf = {}, file = photo.uploadInfo[id].file;

        reader.onload = function(e) {
            var result = this.result;

            // 如果是jpg格式图片，读取图片拍摄方向,自动旋转
            if (file.type == 'image/jpeg'){
                var jpg = new JpegMeta.JpegFile(result, file.name);
                if (jpg.tiff && jpg.tiff.Orientation) {
					
        conf = {
            maxW: 800, //目标宽
            maxH: 800, //目标高
            quality: 0.8, //目标jpg图片输出质量
            orien: 1
        };
                    //设置旋转
				 conf = extend(conf, {
                                     orien: jpg.tiff.Orientation.value
                                     });
                }
            }

            // 压缩
            if (ImageCompresser.support()) {
                var img = new Image();
                img.onload = function() {
                    try {
                        uploadBase64 = ImageCompresser.getImageBase64(this, conf);
                    } catch (e) {
                        //TOOLS.dialog({content:'压缩图片失败',autoClose:true});
                        $('li#li' + id).remove();
                        return false;
                    }
                    if (uploadBase64.indexOf('data:image') < 0) {
                       // TOOLS.dialog({content:'上传照片格式不支持',autoClose:true});
                        $('li#li' + id).remove();
                        return false;
                    }

                    photo.uploadInfo[id].file = uploadBase64;//e.target.result;
                    photo.uploadInfo[id].filename = file.name;
                    $('li#li' + id).find('img').attr('src', uploadBase64);
                    photo.uploadQueue.push(id);
                }
                img.src = ImageCompresser.getFileObjectURL(file);
            } else {
                uploadBase64 = result; 
                if (uploadBase64.indexOf('data:image') < 0) {
                   // TOOLS.dialog({content:'上传照片格式不支持',autoClose:true});
                    $('li#li' + id).remove();
                    return false;
                }
                photo.uploadInfo[id].file = uploadBase64;//e.target.result;
                photo.uploadInfo[id].filename = file.name;
                $('li#li' + id).find('img').attr('src', uploadBase64);
                photo.uploadQueue.push(id);
            }

        }
        reader.readAsBinaryString(photo.uploadInfo[id].file);
    },

    _keys: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', /*用于BASE64转码*/

    base64decode: function(input) {
        var output = '';
        var chr1, chr2, chr3 = '';
        var enc1, enc2, enc3, enc4 = '';
        var i = 0;
        if (input.length%4!=0){
            return '';
        }
        var base64test = /[^A-Za-z0-9\+\/\=]/g;
        if (base64test.exec(input)){
            return '';
        }
        do {
            enc1 = photo._keys.indexOf(input.charAt(i++));
            enc2 = photo._keys.indexOf(input.charAt(i++));
            enc3 = photo._keys.indexOf(input.charAt(i++));
            enc4 = photo._keys.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64){
                output+=String.fromCharCode(chr2);
            }
            if (enc4 != 64){
                output+=String.fromCharCode(chr3);
            }
            chr1 = chr2 = chr3 = '';
            enc1 = enc2 = enc3 = enc4 = '';
        } while (i < input.length);
        return output;
    },

    // 创建上传请求
    createUpload: function(id,act) { 

        if (!photo.uploadInfo[id]) {
            return false;
        }
		
		var path=$('li#li' + id).parent().attr("path");
		var exts=$('li#li' + id).parent().attr("exts");
		if(typeof(exts)=="undefined")exts="";
		if(typeof(path)=="undefined")path="";
        // 图片posturl
		var uploadUrl =   '/BoxAddon/Upload/Index/upload/exts/'+exts+"/path/"+path;//alert(uploadUrl);
		//console.log(uploadUrl);
		 $('li#li' + id).prepend('<div class="maskLay"></div>');
		// 产生进度条
        var progressHtml = '<div class="progress" id="progress'+id+'"><div class="proBar" style="width:0%;"></div></div>';
		 //$('li#li' + id).prepend(progressHtml);
        $('li#li' + id).find('.maskLay').insertAfter(progressHtml);
        //var formData = new FormData();
       // formData.append('filedata', photo.uploadInfo[id].file);
       // formData.append('uid', uid); 
		/*formData.append('tid', topicid);
        formData.append('hash', uploadHash);
		formData.append('token', S_token);*/

        var progress = function(e) {
            if (e.target.response) {
                var result = $.parseJSON(e.target.response);
                if (result.errCode != 0) {
                    // $('#message').val(result.errCode);
                    //TOOLS.dialog({content:'网络不稳定，请稍后重新操作',autoClose:true});
                    removePic(id);
                }
            }

            var progress = $('#progress' + id).find('.proBar');
            if (e.total == e.loaded) {
                var percent = 100;
            } else {
                var percent = 100*(e.loaded / e.total);
            }
            // 控制进度条不要超出
            if (percent > 100) {
                percent = 100;
            }
            progress.css('width', percent + '%');

            if (percent == 100) {
                $('li#li' + id).find('.maskLay').remove();
                $('li#li' + id).find('.progress').remove();
            }
        }

        var removePic = function(id) {
            donePic(id);
            $('li#li' + id).remove();
			var ul=$('li#li' + id).parent();
			photo.has_upload_list(ul,"del");
        }

        var donePic = function(id) {
            photo.isBusy = false;
            photo.uploadInfo[id].isDone = true;
            photo.xhr[id] = null;

            /*var reportObj = {
                'a' : 'upload',
                'uid' : uid || ''
            };
            TOOLS.addReportCount(reportObj);*/
        }

        var complete = function(e) {
            //TOOLS.dialog({content:e.target.response,autoClose:true});
            // 上传结束
            donePic(id);
            /*
             返回值(纯文本) 如：DB|0|1051301|1|0
             DB为固定输出
             第一个0	代表报错信息，0为正常，非零为出错。
             第二个1051301	代表成功上传图片的附件aid
             第三个1	代表是否是图片
             第四个0	代表导致出错的上传文件容量的尺寸，比如1024000,则限制1024000字节以下的
             */ 
				//alert(e.target.response);
			//console.log(e);
            var response = JSON.parse(e.target.response);
			console.log(response);
			//if(response.error)
 		//	var attach = response.msg.split('|')
			//console.log(attach);
			//alert(attach.length);
            if(response.error== 0 ){ 
				var obj =$('li#li' + id);
				obj.attr("name",response.data.name);
				obj.attr("url",response.data.file_url);
                $('li#li' + id).find('.maskLay').remove();
                $('li#li' + id).find('.progress').remove();
				photo.has_upload_list($(obj).parent(),"add");
            }else{
				hiApp.alert(response.msg);
                removePic(id);
            }
		   
        }
		
		

        var failed = function() {
            photo.isBusy = false;
            photo.uploadInfo[id].isDone = true;
            //TOOLS.dialog({content:'网络断开，请稍后重新操作',autoClose:true});
            removePic(id)
        }

        var abort = function() {
            photo.isBusy = false;
            photo.uploadInfo[id].isDone = true;
            //TOOLS.dialog({content:'上传已取消',autoClose:true});
            removePic(id)
        }

        // 创建 ajax 请求
        photo.xhr[id] = new XMLHttpRequest();
        var boundary = '------multipartformboundary' + (new Date).getTime();
		var s = {
            uploadformdata:{ qunid:photo.qunId, topicid: photo.tid},
            uploadinputname:'filedata',
        };
		
        var picdata = photo.uploadInfo[id].file.replace(/data:.+;base64,/, '');
        if(typeof atob == 'function') {
            picdata = atob(picdata);
        } else {
            picdata = photo.base64decode(picdata);
        }
        var builder = photo.getbuilder(s, photo.uploadInfo[id].filename, picdata, boundary);
        photo.xhr[id].open("POST", uploadUrl, true);
        photo.xhr[id].setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
        if(!XMLHttpRequest.prototype.sendAsBinary){//如果XMLHttpRequest没有sendAsBinary
          XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
            function byteValue(x) {
              return x.charCodeAt(0) & 0xff;
            }
            var ords = Array.prototype.map.call(datastr, byteValue);
            var ui8a = new Uint8Array(ords);
            this.send(ui8a.buffer);
          };
        }
        photo.xhr[id].sendAsBinary(builder);
        photo.xhr[id].onerror = function(e) {
            failed();
        };
        photo.xhr[id].onload = function(e) {
            complete(e);
        };
        photo.xhr[id].abort = function(e) {
            abort();
        };
        photo.xhr[id].onsendstream = function(e) {
            progress(e);
        };

    },
    // 上传相关
  initUpload: function() {
		
		if (!photo.isBusy) { 
					$(document).on("touchstart", "#addPic", function () {
						$('#uploadFile').click();
					  });
                } else {
				     hiApp.alert('上传中，请稍后添加');
                     return false;
                }
				
// 文件表单发生变化时
 $(document).on('change', '.uploadFile', function(e) {
	 	   uploadObj = $(this);	
		   var ul=$(this).parent().parent();	
           e = e || window.event;
           var fileList = e.target.files;
           if (!fileList.length) {
               return false;
           }
		   if($(ul).attr("maxUpload")){
			photo.maxUpload=$(ul).attr("maxUpload");
		   }
           for (var i = 0; i<fileList.length; i++) {
                if (photo.countUpload() >= photo.maxUpload) {
				   hiApp.alert('你最多只能上传'+photo.maxUpload+'个文件');
                break;
         	  }

           var file = fileList[i];

           if (!photo.checkPicSize(file)) {
			   hiApp.alert('文件体积过大');
                continue;
           }
          // if (!photo.checkPicType(file)) {
//			   hiApp.alert('上传文件格式不支持');
//                continue;
//           }

           var id = Date.now() + i;
           // 增加到上传对象中, 上传完成后，修改为 true
           photo.uploadInfo[id] = {
                file: file,
                filename: '',
                isDone: false,
           };

           var html = '<li id="li' + id + '"><div class="photoCut"><img src="/Public/images/defaultImg.jpg" class="attchImg" alt="photo"></div>' +
           '<div class="maskLay"></div>' +
           '<a href="javascript:" class="cBtn spr db "  _id="'+id+'">关闭</a></li>';
		   $('.photoList').find('ul').prepend(html);
           photo.previewQueue.push(id);
           }
           // 图片已经上传了 8 张，隐藏 + 号
           if (photo.countUpload() >= photo.maxUpload) {
                $(this).parent().hide();
           }

           // 把输入框清空
           $(this).val('');
        });
		
//删除		
$('.photoList').on("click", '.cBtn', function() {
            var id = $(this).attr('_id');
			var _this=$(this);
			var ul=$(this).parent().parent();
			var li=$(this).parent();
            // 取消这个请求
            if (photo.xhr[id]) {
                photo.xhr[id].abort();
            }
			
            // 图片删除
            $('li#li' + id).remove();
            photo.uploadInfo[id] = null;
			photo.has_upload_list(ul,"del");
			
            // 图片变少了，显示+号
            if (photo.countUpload() < photo.maxUpload) {
                $(ul).find(".uploadFile").parent().show();
            }
        });

        setInterval(function() {
            // 预览
            setTimeout(function() {
                       if (photo.previewQueue.length) {
                       var jobId = photo.previewQueue.shift();
                       photo.uploadPreview(jobId);
                       }
                       }, 1);
            // 上传
            setTimeout(function() {
                       if (!photo.isBusy && photo.uploadQueue.length) {
                       var jobId = photo.uploadQueue.shift();
                           photo.isBusy = true;
                           photo.createUpload(jobId,'topic');
                       }
                       }, 10);
            }, 300);
			
    },
 
    // 检查图片大小
    checkPicSize: function(file) {
        // 8M
        if (file.size > 10000000) {
            return false;
        }
        return true;
    },
    // 检查图片类型
    checkPicType: function(file) {

        if(file.type.indexOf('image/') == 0) {
            return true;
        }
        else {
            var index = file.name.lastIndexOf('.');
            var extName = file.name.substring(index+1).toLowerCase();
            if(extName == 'jpg' || extName == 'jpeg' || extName == 'png' || extName == 'gif' ) {
                return true;
            }
            return false;
        }
    }

    };

    return photo;
})();